import asyncio
from mitmproxy import http, options, ctx
from mitmproxy.tools.dump import DumpMaster
import json
from rapidfuzz import fuzz
import logging
from threading import Thread
# import requests
from soruce import *
# from logging import logger

getQuestion_url = "https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=getQuestion&from=xcx&destination_id=499"
getMemberToday_url = "https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=getMemberToday&from=xcx&destination_id=499"
# 配置日志级别以实现静默输出，这里设置为ERROR级别，仅显示错误信息
logging.getLogger("mitmproxy").setLevel(logging.ERROR)
with open('./data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
title_list = data['title']
answer_list = data['answer']
# https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=getQuestion&from=xcx&destination_id=499
# 获取openid和checkstr
openid = ''
checkstr = ''
# answers_datalist = []
# https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=getMemberToday&from=xcx&destination_id=499&member_id=80345
# 得到row_id和member_id
row_id = ''
member_id = ''
# datalist中
token = ''
#
secret = ''
#
SEND_FLAG = False

LISTENPORT = 8282

HEDAERS = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090819) XWEB/8555'
}


def check_send_flag():
    global SEND_FLAG
    while 1:
        # print(time.strftime('%S', time.localtime(time.time())))
        if SEND_FLAG:
            SEND_FLAG = False
            # 先get这个
            # resp = requests.get(
            #     url=
            #     f"https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=addPlayCount&from=xcx&destination_id=499&openid={openid}&checkstr={checkstr}",
            #     headers=HEDAERS,
            #     verify=False)
            # print(resp.json())
            # # # 再get这个
            # # # https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=savePlayScore&from=xcx&destination_id=499
            # # &openid=oO5mg4vuBmoKNrss9hbLyrg8tuIs&member_id=80345
            # # &score=0&
            # # type=1&groupid=0&token=2498976,1906416,2064240&secret=6070ae9555b07a91cb40bb46251bcd3f&checkstr=44106b4f9f8bd1d98d105dd9c0bc4a30
            # # https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=savePlayScore&from=xcx&destination_id=499
            # # &openid=oO5mg4vuBmoKNrss9hbLyrg8tuIs&member_id=80345
            # # &score=11
            # # &type=1
            # # &groupid=29
            # # &token=2452752,2519568,2154960,1861200,2101680,1762272,2104560,1777392,2589120,2355984,2151072,1902240,2652192,2647296,2081520
            # # &secret=ae341afada837008eb5733711ff09082
            # # &checkstr=44106b4f9f8bd1d98d105dd9c0bc4a30
            # # https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=savePlayScore&from=xcx&destination_id=499
            # # &openid=oO5mg4vuBmoKNrss9hbLyrg8tuIs&member_id=80345&score=27&type=1&groupid=0
            # # &token=%5B2372400,%202213424,%202366064,%202210688,%202585808,%201920528,%201978128,%202722752,%202485584,%201962720,%202388960,%201826784,%202621376,%202092752,%202069712,%202102976,%202318400,%202160864,%202121552,%202408976,%201838304,%202062224,%202463840,%202146608,%202607120,%201774224,%202214000%5D
            # # &secret=8efb2bc14ee07a3a17e715bede609829
            # # &checkstr=44106b4f9f8bd1d98d105dd9c0bc4a30
            # resp = requests.get(
            #     url=
            #     f"https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=savePlayScore&from=xcx&destination_id=499&openid={openid}&member_id={member_id}&score={27}&type=1&groupid=0&token={token}&secret={secret}&checkstr={checkstr}",
            #     headers=HEDAERS,
            #     verify=False)
            # print(resp.json())

        else:
            time.sleep(1)


def get_maxRatio_title(input_string):
    # 初始化最大匹配度和索引
    max_match_ratio = 0
    test_title = ''
    maxTitle = ''
    max_match_index = -1
    for words in input_string['words_result']:
        test_title += words['words']
    for index, title in enumerate(title_list):
        # 使用fuzz.ratio方法计算两个字符串的匹配度
        match_ratio = fuzz.ratio(test_title, title)
        # 如果当前匹配度大于已记录的最大匹配度，则更新最大匹配度和索引
        if match_ratio > max_match_ratio:
            max_match_ratio = match_ratio
            max_match_index = index
            maxTitle = title
    print('匹配率：{} 题干：{}'.format(max_match_ratio, maxTitle))
    return maxTitle.replace('\n', ''), max_match_index


def new_search(
    questionTxt: dict,
    optionsTxt: dict,
    titile_text=None,
    answer_text=None,
    autoclick=False,
):
    # with open('./data.json', 'r', encoding='utf-8') as f:
    #     data = json.load(f)
    #     title_list = data['title']
    #     answer_list = data['answer']

    options_list = optionsTxt["words_result"]
    title, answer_index = get_maxRatio_title(questionTxt)
    if titile_text:
        titile_text.delete('1.0', 'end')
        titile_text.insert('insert', title + '\n')
    answer = answer_list[answer_index]
    maxRatio = 0
    x, y = 0, 0
    for index, option in enumerate(options_list):
        ratio = fuzz.ratio(answer, option['words'])
        if maxRatio < ratio:
            print("选项：{} 匹配率{}".format(index, ratio))
            maxRatio = ratio
            # answer = answer
            if autoclick:
                x = option['location']['left']
                y = option['location']['top']
    if not maxRatio:
        answer = '无法匹配，自行判断\n答案：' + answer
        print(answer)
    if answer_text:
        answer_text.delete('1.0', 'end')
        answer_text.insert('insert', answer)
    return x, y


# 创建自定义主类以加载addons
class QuietMaster(DumpMaster):

    def run(self, *args, **kwargs):
        # 在启动前，进一步配置日志处理器，以达到静默效果
        for handler in logging.getLogger("mitmproxy").handlers:
            handler.setLevel(logging.ERROR)
        return super().run(*args, **kwargs)


# https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=getQuestion&from=xcx&destination_id=499&type=1,2,3,4,5,6,7,8,9,10,11,&openid=oO5mg4vuBmoKNrss9hbLyrg8tuIs&checkstr=44106b4f9f8bd1d98d105dd9c0bc4a30
class ExampleAddon:
    # def request(self, flow: http.HTTPFlow) -> None:
    #     # 在请求阶段也进行过滤，避免不必要的日志
    #     if target_url not in flow.request.pretty_url:
    #         return
    def request(self, flow: http.HTTPFlow) -> None:
        # 这里定义您要忽略的网址，可以使用通配符或者具体的域名
        ignore_hosts = ["cn-jn-lt-plustmp1.natfrp.cloud"]
        # print(f"【请求】{flow.request.pretty_url}")
        # print(f"【请求】{flow.request.host}")
        if flow.request.host in ignore_hosts:
            # 如果请求的主机名在忽略列表中，则直接返回，忽略该请求
            return

    def response(self, flow: http.HTTPFlow) -> None:
        # 在响应阶段进行过滤和处理
        if getQuestion_url in flow.request.pretty_url:
            global title_list
            global answer_list
            global openid
            global checkstr
            global token
            global SEND_FLAG
            params_list = flow.request.pretty_url.split('&')
            openid = params_list[-2].split('=')[-1]
            checkstr = params_list[-1].split('=')[-1]
            title_list = []
            answer_list = []
            print(f"\n【请求】{flow.request.pretty_url}")
            print(f"【响应状态码】{flow.response.status_code}")
            print(f"【openid】{openid}")
            print(f"【checkstr】{checkstr}")
            # print(f"【响应内容】{flow.response.text[:200]}...")
            '''
            以下为特有内容
            '''
            answers_json = flow.response.json()
            # print(f"【响应内容】{flow.response.json()}")
            answers_datalist = answers_json['datalist']
            token = get_token(answers_datalist)[0:27]
            print(f"【token】{token}")
            SEND_FLAG = True
            for data in answers_datalist:
                answers_title = data['title']
                answers_answer = data['answer']
                answers_choose = data[f'chose_{chr(int(answers_answer)+96)}']
                title_list.append(answers_title)
                answer_list.append(answers_choose)
            # print(answers_data)
            with open('data.json', 'w', encoding='utf-8') as f:
                json.dump({
                    'title': title_list,
                    'answer': answer_list
                },
                          f,
                          ensure_ascii=False,
                          indent=4)
        elif getMemberToday_url in flow.request.pretty_url:
            global member_id
            global row_id
            global secret
            params_list = flow.request.pretty_url.split('&')
            member_id = params_list[-1].split('=')[-1]
            print(f"\n【请求】{flow.request.pretty_url}")
            print(f"【响应状态码】{flow.response.status_code}")
            resp_json = flow.response.json()
            row_id = resp_json['data']['row_id']
            print(f"【响应内容】{resp_json}")
            print(f"【member_id】{member_id}")
            print(f"【row_id】{row_id}")
            secret = get_secret(row_id, 27)
            print(f"【secret】{secret}")
        else:
            return


async def start_mitmproxy_async():
    opts = options.Options(
        listen_port=LISTENPORT,  # 自定义监听端口
    )
    master = QuietMaster(opts)
    master.addons.add(ExampleAddon())
    print(f"mitmproxy正在运行，请设置代理到localhost:{LISTENPORT}...")
    await master.run()
    # print("\nmitmproxy已停止。")


def get_answers_web_data():
    try:
        asyncio.run(start_mitmproxy_async())
    except KeyboardInterrupt:
        print("\n手动中断。")


if __name__ == "__main__":
    th = Thread(target=check_send_flag)
    th.daemon = True
    th.start()
    print("按 ctrl C 停止，不要直接关闭")
    get_answers_web_data()
